package com.verification.controller;


import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.verification.bean.User;
import com.verification.custom.InspectorException;

@Controller
public class TestController 
{
	/**
	 * @todo form提交
	 * @author fg
	 * @throws InspectorException 
	 * @date 2016年3月29日
	 */
	@RequestMapping("/formSubmit")
	public ModelAndView formSubmit(@Valid User user,BindingResult result) throws InspectorException {
		if(result.hasErrors())
			throwInspectorException(result);
		return null;
	}
	
    /**
     * @todo 公共抛出后台校验异常的方法
     * @author fg
     * @date 2016年4月6日
     */
    private void throwInspectorException(BindingResult result) throws InspectorException {
        StringBuffer sb = new StringBuffer("<br/>");
        for(FieldError fieldError :result.getFieldErrors()){
        	//errorMessage=err.get(i).getDefaultMessage();//得到错误消息
            sb.append("错误字段："+fieldError.getField()+"<br/>"+" 值 ：" +fieldError.getRejectedValue()+"<br/>");
        }
        throw new InspectorException(sb+"");
	}

	
    /**
     * @todo 后台校验异常捕获
     * @author fg
     * @date 2016年4月6日
     */
    @ExceptionHandler(InspectorException.class)  
    public ModelAndView inspector(InspectorException e,HttpServletRequest request){ 
    	ModelAndView mav = new ModelAndView();
    	mav.setViewName("error.jsp");
    	mav.addObject("msg","<br/>后台校验出现错误："+e.getMessage());
    	
		return mav;
    } 
    

}
